import React from 'react';
import { Card, Table, Button, Input, Modal, Form, Space, Image, Tag, Select, message } from 'antd';

// 主产品库（模仿 admin-web 的 ProductLibrary.vue）
export default function ProductLibrary() {
  // 搜索与分页
  const [searchForm] = Form.useForm();
  const [search, setSearch] = React.useState({ name: '' });
  const [pageIndex, setPageIndex] = React.useState(1);
  const [pageSize, setPageSize] = React.useState(10);
  const [loading, setLoading] = React.useState(false);

  // 素材库数据（模拟）
  const [tableList, setTableList] = React.useState(() => ([
    { id: 1, name: '可乐（素材）', url: 'https://via.placeholder.com/60', uId: 1, pId: 0 },
    { id: 2, name: '雪碧（素材）', url: 'https://via.placeholder.com/60', uId: 1, pId: 0 },
    { id: 3, name: '薯片（素材）', url: 'https://via.placeholder.com/60', uId: 1, pId: 0 },
  ]));

  // 标签集合（模拟）
  const [productTags, setProductTags] = React.useState([
    { id: 1, name: '热销' },
    { id: 2, name: '新品' },
    { id: 3, name: '限时' },
  ]);

  // 新增/编辑商品弹窗（从素材库添加为商品）
  const [dialogProduct, setDialogProduct] = React.useState(false);
  const [form] = Form.useForm();
  const [product, setProduct] = React.useState({});
  const [fromMaterial, setFromMaterial] = React.useState('0');

  const filtered = React.useMemo(() => {
    let data = tableList;
    if (search.name) data = data.filter(i => String(i.name).includes(search.name));
    return data;
  }, [tableList, search]);

  const pageData = React.useMemo(() => {
    const start = (pageIndex - 1) * pageSize;
    return filtered.slice(start, start + pageSize);
  }, [filtered, pageIndex, pageSize]);

  const columns = [
    { title: '名称', dataIndex: 'name', align: 'center' },
    {
      title: '图片',
      dataIndex: 'url',
      align: 'center',
      width: 120,
      render: (url, row) => (
        <Image src={url} width={60} height={60} style={{ cursor: 'pointer' }} />
      ),
    },
    {
      title: '操作',
      fixed: 'right',
      align: 'center',
      render: (_, row) => (
        <Space>
          <Button size="small" type="success" onClick={() => getProductType(row)}>添加为商品</Button>
          <Button size="small" danger onClick={() => delProductType(row)}>删除</Button>
        </Space>
      ),
    },
  ];

  // 搜索
  const onSearchSubmit = async () => {
    const values = await searchForm.validateFields();
    setSearch(values);
    setPageIndex(1);
  };
  const onResetSearch = () => {
    searchForm.resetFields();
    setSearch({ name: '' });
    setPageIndex(1);
  };

  // 操作
  const handlerInsert = () => {
    setFromMaterial('1');
    setDialogProduct(true);
    form.resetFields();
    setProduct({});
  };
  const delProductType = (row) => {
    setTableList(prev => prev.filter(i => i.id !== row.id));
    message.success('删除成功');
  };
  const getProductType = (row) => {
    setFromMaterial('0');
    setDialogProduct(true);
    const init = { name: row.name.replace('（素材）', ''), url: row.url };
    setProduct(init);
    form.setFieldsValue({ ...init });
  };
  const onSave = async () => {
    const values = await form.validateFields();
    // 这里仅模拟保存为商品，实际应调用商品新增接口
    message.success(fromMaterial === '1' ? '素材已新增' : '已从素材添加为商品');
    setDialogProduct(false);
  };

  return (
    <div style={{ display: 'grid', gap: 16 }}>
      <Card variant="borderless">
        <div style={{ display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
          <Button type="primary" onClick={handlerInsert}>新增素材产品</Button>
          <Form form={searchForm} layout="inline" initialValues={search} style={{ display: 'flex', gap: 12 }}>
            <Form.Item name="name" label="名称">
              <Input allowClear placeholder="请输入名称" style={{ width: 220 }} />
            </Form.Item>
            <Space>
              <Button type="primary" onClick={onSearchSubmit}>查询</Button>
              <Button onClick={onResetSearch}>重置</Button>
            </Space>
          </Form>
        </div>
      </Card>

      <Card title="主产品素材库" variant="borderless" styles={{ body: { paddingTop: 8 } }}>
        <Table
          rowKey={(r) => r.id}
          loading={loading}
          dataSource={pageData}
          columns={columns}
          pagination={{
            current: pageIndex,
            pageSize,
            total: filtered.length,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50'],
            onChange: (pi, ps) => { setPageIndex(pi); setPageSize(ps); },
          }}
        />
      </Card>

      {/* 从素材库添加为商品 弹窗 */}
      <Modal title={fromMaterial === '1' ? '新增素材产品' : '添加为商品'} open={dialogProduct} onOk={onSave} onCancel={() => setDialogProduct(false)}>
        <Form form={form} layout="vertical">
          <Form.Item name="name" label="商品名称" rules={[{ required: true, message: '请输入商品名称' }]}> 
            <Input />
          </Form.Item>
          <Form.Item name="goodsTags" label="商品标签"> 
            <Select mode="multiple" allowClear placeholder="选择标签">
              {productTags.map(t => <Select.Option key={t.id} value={t.id}>{t.name}</Select.Option>)}
            </Select>
          </Form.Item>
          <Form.Item name="url" label="图片地址"> 
            <Input placeholder="图片 URL" />
          </Form.Item>
          <Form.Item name="costPrice" label="价格"> 
            <Input type="number" step="0.01" />
          </Form.Item>
          <Form.Item name="no" label="编码"> 
            <Input />
          </Form.Item>
          <Form.Item name="notes" label="备注"> 
            <Input.TextArea rows={3} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}